<template>
    <div class="main_container" style="background-color: #fff;overflow-y: auto;display: flex;">
		<div class="left">
			<div class="part1">
				<img src="https://anhuiyaoying.com/webs/welcome.png" alt="">
				<span>欢迎回来，{{nickName}}</span>
			</div>
			<div class="common_line line_width"></div>
			<div class="part2">
				<div class="item" v-for="item in topData" :key="'top_'+item.id">
					<img :src="item.icon" alt="">
					<div class="sub_item">
						<div>{{item.title}}</div>
						<div>
							<span class="count">{{item.count}}</span>
							<span>{{item.unit}}</span>
							<i v-if="item.showArrow&&item.count>0" class="el-icon-caret-top red" ></i>
							<i v-if="item.showArrow&&item.count<0" class="el-icon-caret-bottom red" ></i>
						</div>
					</div>
				</div>
			</div>
			<div class="common_line line_width"></div>
			<div class="part3">
				<div class="head">
					<div>
						<b>营业额数据</b>
						<span>（近一个月）</span>
					</div>
					<div class="more" @click="changePage('businessCount')">查看更多</div>
				</div>
				<bussinessline :monthDate='monthDate' :monthDay='monthDay'></bussinessline>
			</div>
			<div class="common_line line_width" style="margin-top: -30px;"></div>
			<div class="part4">
				<div class="item">
					<div class="head">
						<div>
							<b>应收应付（TOP 5）</b>
						</div>
						<div class="filter">
							<el-radio-group v-model="cusType" size="mini" fill="#068CEE" @change="radioChange">
								<el-radio-button label="客户"></el-radio-button>
								<el-radio-button label="供货商"></el-radio-button>
							</el-radio-group>
						</div>
					</div>
					<div class="table">
						<el-table :data="tableData" style="width: 100%">
							<el-table-column prop="order" align="center" label="排名"></el-table-column>
							<el-table-column v-if="cusType=='客户'" prop="name" align="center" label="客户姓名"></el-table-column>
							<el-table-column v-else prop="name" align="center" label="供货商名称"></el-table-column>
							<el-table-column prop="total_sum_name" align="center" label="欠款金额"></el-table-column>
						</el-table>
					</div>
				</div>
				<div class="item pd_20">
					<div class="head" style="padding-left: 20px;">
						<div>
							<b>月度利润</b>
						</div>
					</div>
					<pie-chart :pieData="chartData" :customStyle="customStyle" :showLegend="true" :totalValue="totalValue"></pie-chart>
				</div>
			</div>
		</div>
		<div class="right">
			<div class="part1">
				<div class="top">
					<span class="title">常用功能</span>
					<span class="btn" @click="showCustomMenu">自定义</span>
				</div>
				<div class="groups">
					<div class="item" v-for="item in functionData" :key="'func_'+item.id" 
						@click="menuClick(item.redirect_url)">
						<i :class="item.icon_url"></i>
						<span class="desc">{{item.name}}</span>
					</div>
				</div>
			</div>
			<div class="common_line line_width"></div>
			<div class="part1">
				<div class="top">
					<span class="title">当月收支</span>
					<!-- <span class="btn">查看更多</span> -->
				</div>
				<div class="shouzhi">
					<div class="item" v-for="item in curMonthData" :key="'shouzhi_'+item.id">
						<div class="subitem">
							<img :src="item.icon" alt="">
							<span>{{item.title}}</span>
						</div>
						<div class="num">{{'￥'+item.money.toFixed(2)}}</div>
					</div>
				</div>
			</div>
			<div class="common_line line_width"></div>
			<div class="part1">
				<div class="top">
					<span class="title">我的待办</span>
					<span class="btn" @click="changePage('todoList')">查看更多</span>
				</div>
				<div class="todos">
					<div v-if="todoLists&&todoLists.length">
						<div class="item" v-for="item in todoLists" :key="'todo_'+item.id">
							<div class="info">
								<div class="type" :style="{background: item.typeColor}">{{item.todoType}}</div>
								<span>{{item.send_username}}</span>
							</div>
							<div class="date">{{item.send_time}}</div>
						</div>
					</div>
					<el-empty v-else :image-size="80"></el-empty>
				</div>
			</div>
		</div>

		<!-- 自定义菜单 -->
		<el-dialog title="自定义常用功能" :visible.sync="showCustomMenuAlert" width="50%" 
			:close-on-click-modal="false" center append-to-body >
			<div class="custom_menu" >
				<div class="top">
					<span class="title">已添加功能</span>（最多6个，可拖拽排序）
				</div>
				<draggable class="drag_view" v-model="selectList" @end="dragEnd" animation="500">
					<div v-for="item in selectList" :key="'drag_'+item.id" class="item" @click="itemClick(item)">
						<i class="check el-icon-remove remove"></i>
						<i class="menu_icon" :class="item.icon_url"></i>
						<span class="desc">{{item.name}}</span>
					</div>
				</draggable>
				<div class="common_line line_width"></div>
				<div class="top">
					<span class="title">全部功能</span>
				</div>
				<div class="drag_view">
					<div v-for="item in allList" :key="'all_'+item.id" class="item" @click="allItemClick(item)">
						<i :class="item.selected?'el-icon-success':'el-icon-circle-check'" class="check"></i>
						<i :class="item.icon_url" class="menu_icon"></i>
						<span class="desc">{{item.name}}</span>
					</div>
				</div>
			</div>
		</el-dialog>
    </div>
</template>

<script>
	import { getHomeStatistic, getHomeData, getHomeMenus, getHomeAllMenus, getTodoList,
		addHomeMenu, delHomeMenu, sortHomeMenu
	} from "@/api/home";
	import { getCurRoles } from '@/api/login'
	import { getBusinessStatistic } from "@/api/statistics";
	import bussinessline from '@/components/bussinessLine';
	import pieChart from '@/components/pieChart';
	import draggable from 'vuedraggable'

	const moment = require('moment')
    export default {
		name: 'manage',
    	data(){
    		return {
				nickName: '',
				corp_id: '',
				topData: [
					{id: 1, icon: 'https://anhuiyaoying.com/webs/bussiness.png', title: '今日营业额', count: '', unit: '元', showArrow: false},
					{id: 2, icon: 'https://anhuiyaoying.com/webs/order.png', title: '今日订单数', count: '', unit: '个', showArrow: false},
					{id: 3, icon: 'https://anhuiyaoying.com/webs/kedanjia.png', title: '平均客单价', count: '', unit: '元', showArrow: false},
					{id: 4, icon: 'https://anhuiyaoying.com/webs/bijiao.png', title: '营业额较昨日', count: '', unit: '元', showArrow: true}
				],
				monthDate: [],
				monthDay: [],
				cusType: '客户',
				order_pending_rank: [],
				purchase_pending_rank: [],
				tableData: [],
				chartData: [],
				customStyle: {
					width: '380px',
					height: '300px',
					paddingRight: '0'
				},
				functionData: [],  //常用功能
				todoLists: [],
				curMonthData: [],  //当月收支
				showCustomMenuAlert: false,  //自定义菜单
				selectList: [],  //选择的菜单,最多6个,可拖拽排序
				allList: [],  //全部菜单
				totalValue: 0
    		}
    	},
    	components: {
			bussinessline,
			pieChart,
			draggable
    	},
    	mounted(){
			this.corp_id = this.$store.state.corpId;
			this.nickName = this.$store.state.userInfo.username

			getCurRoles({ corp_id: this.corp_id }).then(res => {
				if (!res.data.has_report){
					this.$router.replace('redirectPage')
				}else{
					this.initData()
				}
			})
    	},
        computed: {

        },
    	methods: {
    		initData() {
				this.getLast30Days()
				this.getTopData()
				this.getMonthBussinessData()
				this.getCustomerShouldPayData()
				this.getEveryMonthData()
				this.getFunctionViewData()
				this.getTodoList()
			},
			// 首页统计
			getTopData() {
				getHomeStatistic({corp_id: this.corp_id}).then(res => {
					if (res.code == 200){
						this.topData[0].count = res.data.data[0].order_price
						this.topData[1].count = res.data.data[0].count_total
						this.topData[2].count = res.data.data[0].avg_price
						this.topData[3].count = res.data.data[0].incr_order_price
					}
				})
			},
			// 近一月的营业额数据
			getMonthBussinessData() {
				let param = {
					corp_id: this.corp_id,
					order_type: 'each_day',
					start_date: this.monthDay[0],
					end_date: moment().format('yyyy-MM-DD')
				}
				getBusinessStatistic(param).then(res => {
					let arr = []
					res.data.data.forEach(item => {
						arr.push(item.income)
					})
					this.monthDate = arr
				})
			},
			// 年度利润数据
			getEveryMonthData() {
				let nowDate = new Date()
				let params = {
					corp_id: this.corp_id,
					order_type: 'month',
					start_date: nowDate.getFullYear()+'-01-01'
				} 
				getBusinessStatistic(params).then(res => {
					let chartDatas = []
					let total = 0
					res.data.data.forEach(item => {
						if (item.turnover >= 0){  //亏损的不展示
                        	chartDatas.push({
								name: item.date + '月',
								value: item.turnover
							})
						}
						total = this.$common.plusFloat(total, parseFloat(item.turnover))
					})
					this.totalValue = total
					this.chartData = chartDatas
				})
			},
			// 动态计算过去 30 天的日期
			getLast30Days() {
				const today = new Date();
				// 从今天开始向前推 30 天
				for (let i = 1; i <= 30; i++) {
					const date = new Date(today);
					date.setDate(today.getDate() - i);  // 设置为今天减去 i 天
					this.monthDay.unshift(moment(date).format('yyyy-MM-DD'));  // 将日期格式化为 YYYY-MM-DD
				}
			},
			// 获取应收应付数据
			getCustomerShouldPayData() {
				getHomeData({corp_id: this.corp_id}).then(res => {
					let datas = res.data.data
					this.order_pending_rank = datas.order_pending_rank.filter((item, index) => {
						item.order = index+1
						item.name = item.customer.name
						item.total_sum_name = item.total_sum.toFixed(2)
						return item
					})
					this.purchase_pending_rank = datas.purchase_pending_rank.filter((item, index) => {
						item.order = index+1
						item.name = item.supplier.name
						item.total_sum_name = item.total_sum.toFixed(2)
						return item
					})
					this.tableData = this.order_pending_rank
					this.curMonthData = [
						{id: 1, icon: 'https://anhuiyaoying.com/webs/xiaoshoue.png', title: '销售额', money: datas.sale_order_price_sum},
						{id: 2, icon: 'https://anhuiyaoying.com/webs/zonglirun.png', title: '总利润', money: datas.profit_sum},
						{id: 3, icon: 'https://anhuiyaoying.com/webs/caigouzhichu.png', title: '采购支出', money: datas.purchase_sold_price_sum},
						{id: 4, icon: 'https://anhuiyaoying.com/webs/richangzhichu.png', title: '日常支出', money: datas.expenditure_sum},
						{id: 5, icon: 'https://anhuiyaoying.com/webs/shoukuan.png', title: '应收款', money: datas.sale_pending_payment_sum},
						{id: 6, icon: 'https://anhuiyaoying.com/webs/fukuan.png', title: '应付款', money: datas.purchase_pending_payment_sum}
					]
				})
			},
			// 获取常用功能区数据
			getFunctionViewData(callback) {
				getHomeMenus({
					corp_id: this.corp_id,
					menu_type: 1
				}).then(res => {
					let datas = res.data
					if (datas.length > 6){
						datas = datas.slice(0, 6)
					}	
					this.functionData = datas
					callback && callback(datas)
				})
			},
			// 获取全部菜单
			getAllMenuList() {
				let that = this
				this.getFunctionViewData(function(callback) {
					that.selectList = callback
					getHomeAllMenus({
						corp_id: that.corp_id,
						menu_type: 1
					}).then(res => {
						that.allList = res.data.filter(item => {
							item.selected = false
							that.selectList.forEach(_item => {
								if (_item.id === item.id){
									item.selected = true
								}
							})
							return item
						})
					})
				})
			},
			// 获取待办列表
			getTodoList() {
				getTodoList({
					corp_id: this.corp_id,
					status: '待审核'
				}).then(res => {
					let list = res.data.Todo_Lists.filter(item => {
						item.send_time = item.send_time.replace('T', ' ').substring(0, 10)
						item.send_username = item.send_user.username
						let type = ''
						switch (item.big_type){
							case 'purchase':
								type = '采购单'
								item.typeColor = '#f5ba57'
								break;
							case 'sale':
								type = '销售单'
								item.typeColor = '#068cee'
								break;
							case 'clock_in':
								type = '考勤'
								item.typeColor = '#bb52c6'
								break;
							default:
								break;
						}
						item.todoType = type
						return item
					})
					this.todoLists = list
				})
			},
			// 客户、供货商切换
			radioChange(val) {
				if (val == '客户'){
					this.tableData = this.order_pending_rank
				}else{
					this.tableData = this.purchase_pending_rank
				}
			},
			// 常用功能点击事件
			menuClick(url) {
				this.$router.push(url);
			},
			// 自定义常用功能
			showCustomMenu() {
				this.getAllMenuList()
				this.showCustomMenuAlert = true
			},
			// 拖拽结束回调
			dragEnd(e) {
				this.selectList = this.selectList.filter((item, index) => {
					item.sort = index+1
					return item
				})
				this.updateMenuSort()
			},
			itemClick(item) {
				this.removeItem(item.id)
			},
			allItemClick(item) {
				if (item.selected){
					return
				}
				if (this.selectList.length === 6){
					this.$message({
						showClose: true,
						message: '最多设置6个',
						type: 'warning'
					});
					return
				}
				this.addItem(item.id)
			},
			// 添加菜单
			addItem(id) {
				addHomeMenu({
					index_menu_id: id,
					corp_id: this.corp_id,
					menu_type: 1
				}).then(res => {
					this.getAllMenuList()
				})
			},
			// 移除菜单
			removeItem(id) {
				delHomeMenu({
					index_menu_id: id,
					corp_id: this.corp_id,
					menu_type: 1
				}).then(res => {
					this.getAllMenuList()
				})
			},
			// 更新菜单排序
			updateMenuSort() {
				let sortArray = []
				this.selectList.forEach(item => {
					sortArray.push({
						index_menu_id: item.id,
						sort: item.sort
					})
				})
				sortHomeMenu({
					corp_id: this.corp_id,
					index_menu_id_sort: sortArray
				}).then(res => {
					this.getAllMenuList()
				})
			},
			// 跳转页面
			changePage(url) {
				this.$router.push(url)
			}
    	}
    }
</script>

<style lang="less" scoped>
	@import '../style/mixin';
	.left {
		position: relative;
		// height: 100%;
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		border-right: 5px solid #f0f0f0;
		.part1 {	
			font-size: 15px;
			font-weight: bold;
			display: flex;
			align-items: center;
			padding: 30px 0 20px 20px;
			img {
				width: 20px;
				height: 20px;
				margin-right: 12px;
			}
		}
		.part2 {
			height: 60px;
			padding: 15px 0;
			display: flex;
			align-items: center;
			justify-content: space-around;
			.item {
				display: flex;
				align-items: center;
				img {
					width: 46px;
					height: 46px;
					margin-right: 10px;
				}
				.sub_item {
					display: inline-flex;
					flex-direction: column;
					font-size: 13px;
					.count {
						font-size: 18px;
						font-weight: bold;
					}
					.red {
						color: red;
						font-size: 18px;
					}
				}
			}
		}
		.part3 {
			padding: 20px 10px 10px 20px;
			.head {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 14px;
				span {
					color: #a0a0a0;
					font-size: 13px;
				}
				.more {
					color: @blue;
					padding-right: 25px;
					&:hover {
						cursor: pointer;
					}
				}
			}
		}
		.part4 {
			display: flex;
			padding: 0 10px 0 20px;
			.item {
				padding: 20px 0;
				width: 50%;
				.head {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 14px;
					.more {
						color: @blue;
						&:hover {
							cursor: pointer;
						}
					}
				}
				.table {
					margin-top: 10px;
				}
			}
			.pd_20 {
				border-left: 5px solid #f0f0f0;
				margin-left: 20px;
			}
		}
	}
	.right {
		position: relative;
		display: flex;
		flex-direction: column;
		// justify-content: space-between;
		float: none;
		// height: 100%;
		width: 400px;
		.part1 {
			padding: 20px 20px 10px 20px; 
			.top {
				display: flex;
				align-items: center;
				justify-content: space-between;
				.title {
					font-size: 14px;
					font-weight: bold;
				}
				.btn {
					font-size: 14px;
					color: @blue;
					&:hover {
						cursor: pointer;
					}
				}
			}
			.groups {
				margin-top: 10px;
				display: flex;
				flex-wrap: wrap;
				justify-content: space-around;
				.item {
					width: 33.33%;
					// flex: 0 0 calc(33.333% - 10px);
					margin: 5px 0;  
					box-sizing: border-box;
					padding: 10px 0;   
					display: inline-flex;
					align-items: center;
					flex-direction: column;
					i {
						font-size: 24px;
						color: @blue;
					}
					.desc {
						font-size: 14px;
						margin-top: 10px;
					}
					&:hover {
						cursor: pointer;
					}
				}
			}
			.todos {
				margin-top: 20px;
				.item {
					display: flex;
					align-items: center;
					justify-content: space-between;
					font-size: 14px;
					margin-bottom: 10px;
					.info {
						display: inline-flex;
						align-items: center;
						.type {
							width: 46px;
							height: 22px;
							line-height: 22px;
							border-radius: 10px;
							text-align: center;
							font-size: 12px;
							color: #fff;
							margin-right: 15px;
						}
					}
				}
			}
			.shouzhi {
				margin-top: 20px;
				display: flex;
				flex-wrap: wrap;	
				justify-content: space-around;
				align-items: center;
				.item {
					flex: 0 0 50%;
					display: flex;
					flex-direction: column;
					align-items: center;
					box-sizing: border-box;
					padding: 10px;
					font-size: 13px;
					.subitem {
						display: inline-flex;
						align-items: center;
						img {
							width: 20px;
							height: 20px;
							margin-right: 5px;
						}
					}
					.num {
						margin-top: 10px;
						font-size: 16px;
						color: #aaa;
					}
				}
			}
		}
	}
	.custom_menu {
		padding: 0 20px;
		width: 100%;
		.top {
			font-size: 14px;
			color: #a0a0a0;
			padding: 10px 0;
			.title {
				font-size: 15px;
				font-weight: bold;
				color: #333;
			}
		}
		.drag_view {
			margin-top: 10px;
			display: flex;
			flex-wrap: wrap;
			width: 100%;
			.item {
				flex: ~"0 0 calc(25% - 10px)";
				margin: 5px;  
				box-sizing: border-box;
				padding: 10px 0;   
				display: inline-flex;
				align-items: center;
				flex-direction: column;
				position: relative;
				.check {
					position: absolute;
					right: 30px;
					top: 0;
					font-size: 18px;
					color: @blue;
				}
				.remove {
					color: red;
				}
				.menu_icon {
					font-size: 24px;
					color: @blue;
				}
				.desc {
					font-size: 14px;
					margin-top: 10px;
				}
				&:hover {
					cursor: pointer;
				}
			}
		}
	}
</style>

<style scoped>
@media screen and (max-width: 1912px) {
	.main_container .right {
		width: 400px;
	}
}
@media screen and (max-width: 1600px) {
	.main_container .right {
		width: 320px;
	}
}
@media screen and (max-width: 1440px) {
	.main_container .right {
		width: 300px;
	}
}
@media screen and (max-width: 1280px) {
	.main_container .right {
		width: 280px;
	}
}
.main_container {
	/* height: 100% !important; */
	padding: 0 !important;
}
</style>
